using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using SpoilsDataSet;

namespace SpoilsInventory
{
    class Common
    {


        internal const int OPEN_BETA = 0;
        internal const int FIRST_EDITION = 1;
        internal const int FIRST_EDITION_PART_2 = 2;
        internal const int STAPLE_RESOURCE = 999;

        internal static LocalData LocalDataSet;

        internal static string DataFilePath(string applicationPath)
        {
            return System.IO.Path.Combine(GetDataDirectory(applicationPath), "CardData.xml");
        }

        internal static string InventoryFilePath(string applicationPath)
        {
            return System.IO.Path.Combine(GetDataDirectory(applicationPath), "Inventory.xml");
        }

        internal static bool DataFileExists(string applicationPath)
        {
            return System.IO.File.Exists(DataFilePath(applicationPath));
        }

        internal static bool InventoryFileExists(string applicationPath)
        {
            return System.IO.File.Exists(InventoryFilePath(applicationPath));
        }

        private static String GetDataDirectory(string applicationPath)
        {
            if (!System.IO.Directory.Exists(System.IO.Path.Combine(applicationPath, "Data")))
                System.IO.Directory.CreateDirectory(System.IO.Path.Combine(applicationPath, "Data"));

            return System.IO.Path.Combine(applicationPath, "Data");
        }

        private static bool mAlreadyAskedImageDir = false;
        internal static string GetImageDirectory(string applicationPath)
        {

            


            string aImageDirectory = GetAppSetting(applicationPath,"ImageDirectory");
            if (aImageDirectory == "" || !System.IO.Directory.Exists(aImageDirectory))
            {
                if (!mAlreadyAskedImageDir)
                {
                    mAlreadyAskedImageDir = true;

                    System.Windows.Forms.DialogResult aLookResult = System.Windows.Forms.MessageBox.Show("Image directory not found.  Do you want to browse for the folder?", "Look for Images?", System.Windows.Forms.MessageBoxButtons.YesNo);
                    if (aLookResult == System.Windows.Forms.DialogResult.Yes)
                    {
                        System.Windows.Forms.FolderBrowserDialog aFolderBrowser = new System.Windows.Forms.FolderBrowserDialog();
                        if (aFolderBrowser.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            SetAppSetting(applicationPath, "ImageDirectory", aFolderBrowser.SelectedPath);
                        }
                    }
                }
            }



            return GetAppSetting(applicationPath, "ImageDirectory");
               

        }

        internal static string GetAppSetting(string applicationPath,string settingName)
        {
            string aFileName = System.IO.Path.Combine(GetDataDirectory(applicationPath), "AppSettings.xml");

            if (LocalDataSet.AppSettings.Count == 0)
                if (System.IO.File.Exists(aFileName))
                    LocalDataSet.AppSettings.ReadXml(aFileName);

            LocalData.AppSettingsRow aReturnRow = LocalDataSet.AppSettings.FindBySettingName(settingName);

            if (aReturnRow == null || aReturnRow.SettingValue == null)
                return "";
            else
                return aReturnRow.SettingValue;


        }

        internal static void SetAppSetting(string applicationPath,string settingName, string settingValue)
        {
            string aFileName = System.IO.Path.Combine(GetDataDirectory(applicationPath), "AppSettings.xml");

            if (LocalDataSet.AppSettings.Count == 0)
                if (System.IO.File.Exists(aFileName))
                    LocalDataSet.AppSettings.ReadXml(aFileName);

            LocalData.AppSettingsRow aValueRow = LocalDataSet.AppSettings.FindBySettingName(settingName);

            if (aValueRow == null)
                aValueRow = LocalDataSet.AppSettings.AddAppSettingsRow(settingName, settingValue);
            else
                aValueRow.SettingValue = settingValue;

            LocalDataSet.AppSettings.WriteXml(aFileName, XmlWriteMode.WriteSchema);
        }

        internal static void SetGridColumnOrder(string applicationPath,string formName, System.Windows.Forms.DataGridView theGrid)
        {
            string[] aGridColumns = GetAppSetting(applicationPath,formName + "." + theGrid.Name + ".ColumnOrder").Split(";".ToCharArray());

            for (int i = 0; i < aGridColumns.Length; i++)
            {
                if(aGridColumns[i] != "")
                    theGrid.Columns[aGridColumns[i]].DisplayIndex = i;
            }
        }

        internal static string ImagePath(string applicationPath, int editionNumber,string cardName)
        {
            string aFileDir = System.IO.Path.Combine(Common.GetImageDirectory(applicationPath), Common.LocalDataSet.Editions.FindByNumber(editionNumber).Name);
            string aFileName = System.IO.Path.Combine(aFileDir, cardName + ".full.jpg");

            return aFileName;
        }



        internal static void BuildInventoryList(string applicationPath)
        {
            foreach (LocalData.CardRow aCardRow in LocalDataSet.Card.Rows)
            {
                if (LocalDataSet.Inventory.FindByEditionNumber(aCardRow.Edition, aCardRow.Number) == null)
                    LocalDataSet.Inventory.AddInventoryRow(LocalDataSet.Editions.FindByNumber(aCardRow.Edition), aCardRow.Number, 0, 0, "");
            }

            SaveInventory(applicationPath);
            
        }

        internal static void SaveInventory(string applicationPath)
        {
            LocalDataSet.Inventory.WriteXml(System.IO.Path.Combine(Common.GetDataDirectory(applicationPath), "Inventory.xml"), XmlWriteMode.WriteSchema);
        }

        internal static void LoadEditions()
        {
            SpoilsDataSet.Helper.LoadEditions(LocalDataSet.Editions);
        }


        internal static void FormatGridCell(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
        {
            System.Windows.Forms.DataGridView aGrid = (System.Windows.Forms.DataGridView)sender;

            switch (aGrid.Columns[e.ColumnIndex].Name)
            {
                case "Strength":
                    if (e.Value != null && e.Value.ToString() != "" && (int)e.Value == -1)
                        e.Value = "";

                    break;
                case "Life":
                    if (e.Value != null && e.Value.ToString() != "" && (int)e.Value == -1)
                        e.Value = "";

                    break;
                case "Speed":
                    if (e.Value != null && e.Value.ToString() != "" && (int)e.Value == -1)
                        e.Value = "";
                    break;
            }
        }
        



       

        internal static void RefreshCardDisplayData()
        {
            LocalDataSet.CardDisplayData.Clear();

            foreach (LocalData.CardRow aCardRow in LocalDataSet.Card)
            {
                LocalDataSet.CardDisplayData.AddCardDisplayDataRow(aCardRow.Edition, aCardRow.Number, aCardRow.EditionsRow.Name, aCardRow.Trade, aCardRow.Name, aCardRow.Rarity, aCardRow.Cost, aCardRow.Threshold, aCardRow.ThresholdType, aCardRow.Type, aCardRow.Subtype, aCardRow.Strength, aCardRow.Life, aCardRow.Speed, aCardRow.CardText);
            }
        }

        internal static void RefreshInventoryDisplayData()
        {
           
            LocalDataSet.InventoryDisplayData.InventoryDisplayDataRowChanged -= new LocalData.InventoryDisplayDataRowChangeEventHandler(InventoryDisplayData_InventoryDisplayDataRowChanged);

            LocalDataSet.InventoryDisplayData.Clear();

            foreach (LocalData.CardRow aCardRow in LocalDataSet.Card)
            {
                LocalData.InventoryRow aInventoryRow = LocalDataSet.Inventory.FindByEditionNumber(aCardRow.Edition, aCardRow.Number);
                LocalDataSet.InventoryDisplayData.AddInventoryDisplayDataRow(aCardRow.Edition, aCardRow.Number,aCardRow.Trade, aCardRow.Rarity,aCardRow.Name, aCardRow.EditionsRow.Name, aCardRow.Type, aCardRow.Subtype,aCardRow.Cost, aCardRow.Threshold, aCardRow.Strength, aCardRow.Life,aCardRow.Speed, aInventoryRow.NormalCount, aInventoryRow.FoilCount, aInventoryRow.Notes);
            }

            LocalDataSet.InventoryDisplayData.InventoryDisplayDataRowChanged += new LocalData.InventoryDisplayDataRowChangeEventHandler(InventoryDisplayData_InventoryDisplayDataRowChanged);
        }

        static void InventoryDisplayData_InventoryDisplayDataRowChanged(object sender, LocalData.InventoryDisplayDataRowChangeEvent e)
        {
            LocalData.InventoryRow aRow = LocalDataSet.Inventory.FindByEditionNumber(e.Row.Edition, e.Row.Number);
            
            aRow.NormalCount = e.Row.NormalCount;
            aRow.FoilCount = e.Row.FoilCount;
            aRow.Notes = e.Row.Notes;
            
        }



        internal static void RefreshPlaysetData(bool combineBetaAndFirstEdition)
        {
            LocalDataSet.InventoryPlaysetData.Clear();


            foreach (LocalData.CardRow aCardRow in LocalDataSet.Card)
            {
                LocalData.InventoryPlaysetDataRow aPlaysetRow = LocalDataSet.InventoryPlaysetData.FindByEditionCardName(aCardRow.Edition, aCardRow.Name);
                LocalData.InventoryRow aInventoryRow = LocalDataSet.Inventory.FindByEditionNumber(aCardRow.Edition, aCardRow.Number);

                if (aPlaysetRow == null)
                {                    
                    int aNormalCount = Math.Min(4, aInventoryRow.NormalCount);
                    int aNormalExtra = Math.Max(0, aInventoryRow.NormalCount - 4);
                    int aFoilCount = Math.Min(4, aInventoryRow.FoilCount);
                    int aFoilExtra = Math.Max(0, aInventoryRow.FoilCount - 4);
                    int aTotalCount = Math.Min(4, aInventoryRow.NormalCount + aInventoryRow.FoilCount);
                    int aTotalExtra = Math.Max(0, (aInventoryRow.NormalCount + aInventoryRow.FoilCount) - 4);

                    int aEdition = aCardRow.Edition;
                    string aRarity = aCardRow.Rarity;

                    if (combineBetaAndFirstEdition && aEdition == Common.OPEN_BETA)
                    {
                        aEdition = Common.FIRST_EDITION;

                        DataRow[] aCardRows = LocalDataSet.Card.Select("Edition=" + aEdition.ToString() + " and Name='" + aCardRow.Name.Replace("'","''") + "'");
                        if (aCardRows.Length == 0)
                            continue;
                        else
                            aRarity = aCardRows[0]["Rarity"].ToString();

                    }



                    string aEditionName = LocalDataSet.Editions.FindByNumber(aEdition).Name;

                    LocalDataSet.InventoryPlaysetData.AddInventoryPlaysetDataRow(aEdition, aEditionName, aCardRow.Number, aCardRow.Name, aRarity, aCardRow.Type, aCardRow.Subtype, aNormalCount, aFoilCount, aNormalExtra, aFoilExtra, aTotalCount, aTotalExtra, aCardRow.Trade);
                }
                else
                {
                    aPlaysetRow.NormalCount = Math.Min(4, aInventoryRow.NormalCount + aPlaysetRow.NormalCount);
                    aPlaysetRow.NormalExtra = Math.Max(0, aInventoryRow.NormalCount + aPlaysetRow.NormalExtra - 4);
                    aPlaysetRow.FoilCount = Math.Min(4, aInventoryRow.FoilCount + aPlaysetRow.FoilCount);
                    aPlaysetRow.FoilExtra = Math.Max(0, aInventoryRow.FoilCount + aPlaysetRow.FoilExtra - 4);

                    aPlaysetRow.TotalCount = Math.Min(4, aPlaysetRow.NormalCount + aPlaysetRow.FoilCount);
                    aPlaysetRow.TotalExtra = Math.Max(0, (aPlaysetRow.NormalCount + aPlaysetRow.FoilCount) - 4);
                }
            }
        }

        internal static int IsNull(object theValue, int alternateValue)
        {
            if (theValue == null || theValue.ToString().Length == 0 || theValue.ToString() == "NaN")
                return alternateValue;
            else
                return Convert.ToInt32(theValue);
        }
    }
}
